import { useNoteStore } from '../stores/noteStore'
import { onMounted } from 'vue'

export function useNotes() {
  const store = useNoteStore()
  
  // 从localStorage加载数据
  function loadFromLocalStorage() {
    const savedData = localStorage.getItem('note-paper')
    if (savedData) {
      const { tags, notes, selectedTagId } = JSON.parse(savedData)
      store.tags = tags || []
      store.notes = notes || []
      store.selectedTagId = selectedTagId || 'all'
    }
  }
  
  // 保存数据到localStorage
  function saveToLocalStorage() {
    const data = {
      tags: store.tags,
      notes: store.notes,
      selectedTagId: store.selectedTagId
    }
    localStorage.setItem('note-paper', JSON.stringify(data))
  }
  
  // 初始化时加载数据
  onMounted(() => {
    loadFromLocalStorage()
  })
  
  // 监听数据变化并保存
  watch(() => store.tags, saveToLocalStorage, { deep: true })
  watch(() => store.notes, saveToLocalStorage, { deep: true })
  watch(() => store.selectedTagId, saveToLocalStorage)
  
  return {
    loadFromLocalStorage,
    saveToLocalStorage
  }
}